var workOutputController = require('../../../Report/server/controllers/WorkOutput.server.controller'),
    periodOutputController = require('../../../Report/server/controllers/PeriodOutput.server.controller'),
    userController = require('../../../User/server/controllers/users.server.controller'),
    departmentController = require('../../../CBO/server/controllers/Department.server.controller'),
    BaseFun = require('../../../Base/server/controllers/Function'),
    _ = require('lodash'),
    mongoose = require('mongoose'),
    Q = require("q");
//根据终端设备UniqueID查找工位对应的工位和作业集合
exports.queryWorkOutput = function(req, res) {
    var body = req.body;
    var dpt = body.dpt;
    var condition = { Department : dpt}
    workOutputController.queryWorkRecord(condition, function(err, records) {
        if (err) {
            res.json({
                Data: null,
                Error: err
            });
        } else {
            res.json({
                Data: records,
                Error: null
            });
        }
    });
};

exports.getPersonOutputByDate = function (req, res) {
    var data = req.body;
    var startDay = data.startDay,
        endDay = data.endDay,
        department = data.department;
    departmentController.findSubDepartmentsDeep(department).then(function (dpts) {
        dpts.push(department);
        return findDptWorkOutput(startDay, endDay, dpts);
    }).then(function (personDatas) {
        return populateUser(personDatas);
    }).then(function (items) {
        var itemTemps = [];
        for (var i = 0; i < items.length; i++) {
            if(items[i].User){
                itemTemps.push({
                    _id:items[i].User._id,
                    user:items[i].User.Name,
                    department:items[i].User.Department.Name,
                    num:items[i].CompleteQtyCount
                })
            }  
        }
        res.json({
            Data: itemTemps,
            Error: null
        });
    }).catch(function (err) {
        res.json({
            Data: null,
            Error: err
        });
    })
    .done();
};
//获取用户作业产量数据详情
exports.getDetailPersonOutput = function (req, res) {
    var data = req.body;
    var startDay = data.startDay,
        endDay = data.endDay,
        userId = data.userId,
        department = data.department;
    departmentController.findSubDepartmentsDeep(department).then(function (dpts) {
        dpts.push(department);
        return findPersonDptWorkOutput(startDay, endDay, dpts, userId);
    }).then(function (workDatas) {
        return populateWork(workDatas);
    }).then(function (populateWorkDatas) {
        return populateItemMaster(populateWorkDatas);
    }).then(function (populateWorkItemDatas) {
        var resultData = getPersonWorkByItem(populateWorkItemDatas);
        res.json({
            Data: resultData,
            Error: null
        });
    }).catch(function (err) {
        res.json({
            Data: null,
            Error: err
        });
    })
    .done();
};

//查找用户关联表的数据
function populateUser (datas) {
    var deferred = Q.defer();

    var barcodeModel = mongoose.model('User');
    barcodeModel.populate(datas, {
        path: 'User', 
        select: 'Code Name Department',
        populate: [{
            path: 'Department',
            model: 'Department',
            select: 'Code Name'
        }]}, function (err, results) {
        if (err) {
            deferred.reject(err);
        }else{
            deferred.resolve(results);
        }
        
    });

    return deferred.promise;
}

//查找作业关联表的数据
function populateWork (datas) {
    var deferred = Q.defer();

    var workModel = mongoose.model('Work');
    workModel.populate(datas, {
        path: 'Work', 
        select: 'Code Name'
        }, function (err, results) {
        if (err) {
            deferred.reject(err);
        }else{
            deferred.resolve(results);
        }
        
    });

    return deferred.promise;
}

function populateItemMaster (works) {
    var deferred = Q.defer();
    var promises = [];
    works.forEach(function (work) {
        promises.push(populateItemMasters(work.ItemMasters));   
    });
    Q.all(promises).then(function (results) {
        
        deferred.resolve(works);
    }, function(err) {
        deferred.reject(err);
    });

    return deferred.promise;
}
function populateItemMasters(datas) {
    var deferred = Q.defer();

    var itemMasterModel = mongoose.model('ItemMaster');
    itemMasterModel.populate(datas, {
        path: 'ItemMaster', 
        select: 'Code Name'
        }, function (err, results) {
        if (err) {
            deferred.reject(err);
        }else{
            deferred.resolve(results);
        }
        
    });

    return deferred.promise;
}

//Aggregate查找
//按对应部门和时间段匹配的，
//按人员分类统计的CompleteQty数量
function findDptWorkOutput(startDay, endDay, dpts){
    var deferred = Q.defer();
    var args = [];
        args.push({
            $match: {
                BizDate: {
                    $gte:new Date(startDay+" 00:00:00"),
                    $lte:new Date(endDay+" 23:59:59")
                },
                Department: {
                    $in: dpts
                }
            }
        });
        args.push({
            $unwind:{
                path: "$Users"
            } 

        });
        args.push({
            $group: {
                _id: "$Users",
                CompleteQtyCount: {
                    $sum: "$CompleteQty"
                }
            }
        });
        args.push({
            $project: {
                User: "$_id",
                CompleteQtyCount: "$CompleteQtyCount",
                _id: 0
            }
        });
        workOutputController.workOutputAggregate(args, function (err, results) {
            if (err) {
                deferred.reject(err);
            } else {
                deferred.resolve(results || []);
            }
        });
    
    return deferred.promise; 
}
//Aggregate查找
//先$unwind用户组数据
//按对应人和时间段和部门匹配的，
//按人员分类统计的CompleteQty数量
function findPersonDptWorkOutput(startDay, endDay, dpts, userId){
    var deferred = Q.defer();
    var user_id = mongoose.Types.ObjectId(userId);  
    var args = [];
        args.push({
            $unwind:{
                path: "$Users"
            } 
        });
        args.push({
            $match: {
                BizDate: {
                    $gte:new Date(startDay+" 00:00:00"),
                    $lte:new Date(endDay+" 23:59:59")
                },
                Department: {
                    $in: dpts
                },
                Users: user_id 
            }
        });
        args.push({
            $group: {
                _id: "$Work",
                ItemMasters: {$push:"$$ROOT"},
                WorkSum: {
                    $sum: "$CompleteQty"
                }
            }
        });
        args.push({
            $project: {
                Work: "$_id",
                ItemMasters: "$ItemMasters",
                WorkSum: "$WorkSum",
                _id: 0
            }
        });
        workOutputController.workOutputAggregate(args, function (err, results) {
            if (err) {
                deferred.reject(err);
            } else {
                deferred.resolve(results || []);
            }
        });
    
    return deferred.promise; 
}


//用户的按作业分组的物料数据再按物料去分组
function getPersonWorkByItem(_works){
        //统计每个作业的每个物料的数量
        var userWDatas = [];
        
        for (var f = 0; f < _works.length; f++) {
            var _items = _works[f].ItemMasters;
            //每个人每个作业有几个物料
            
            var ItemMasters = [{
                _id:_items[0].ItemMaster._id,
                Code:_items[0].ItemMaster.Code,
                Name:_items[0].ItemMaster.Name
            }];
            for (var i = 0; i < _items.length; i++) {
                var repeat = false;
                for (var j = 0; j < ItemMasters.length; j++) {
                    if (_items[i].ItemMaster._id.toString() === ItemMasters[j]._id.toString()) {
                        repeat = true;
                        break;
                    }
                }
                if (!repeat) {
                    ItemMasters.push({
                         _id:_items[i].ItemMaster._id,
                        Code:_items[i].ItemMaster.Code,
                        Name:_items[i].ItemMaster.Name
                    });
                }
            }
            var imDatas = [];
          
            //统计每个作业每个物料的数量
            for (var m = 0; m < ItemMasters.length; m++) {
                var num = 0;
                for (var n = 0; n < _items.length; n++) {
                    if(ItemMasters[m]._id.toString() === _items[n].ItemMaster._id.toString()){
                        num += _items[n].CompleteQty;
                    }
                }
                imDatas.push({
                    itemName: ItemMasters[m].Code,
                    num: num
                });    
            }
            
            userWDatas.push({
                ItemMasters: imDatas,
                Work: _works[f].Work.Name,
                WorkSum: _works[f].WorkSum
            });
        }

        return userWDatas;
}



//通过部门和时间段查找当其产量
exports.getPeriodOutputByDate = function (req, res) {
    var data = req.body;
    var startDay = data.startDay,
        endDay = data.endDay,
        department = data.department;
    
    var listData = [];
    var resultData = {};
    periodOutputController.getPeriodOutputByDate(startDay, endDay, department, function (err, result) {
        // console.log("getBarcodeData-------------"+result);
        if (err) {
            res.json({
                Data: null,
                Error: err
            });
        } else {
            if (result == null) {
                var newErr = new Error();
                newErr.leval = 9;
                newErr.title = '当期产量查询失败';
                newErr.message = '未找到对应的当期产量！';
                res.json({
                    Data: null,
                    Error: newErr
                });
            } else {
                //统计累计的转入，完工，在制，库存
                var sumTransInQty = 0,sumCompleteQty = 0,sumEWIP = 0,sumEOH = 0;
                for (var i = 0; i < result.length; i++) {
                    var r = result[i];
                    listData.push({
                        _id: r._id,
                        ItemMasterCode: r.ItemMaster.Code,
                        TransInQty: r.TransInQty,
                        CompleteQty: r.CompleteQty,
                        EWIP: r.EWIP,
                        EOH: r.EOH
                    });
                    sumTransInQty += r.TransInQty;
                    sumCompleteQty += r.CompleteQty;
                    sumEWIP += r.EWIP;
                    sumEOH += r.EOH;
                }
                resultData = {
                    listData: listData,
                    sumTransInQty: sumTransInQty,
                    sumCompleteQty: sumCompleteQty,
                    sumEWIP: sumEWIP,
                    sumEOH: sumEOH
                }
                res.json({
                    Data: resultData,
                    Error: null
                });
            }
        }
    });
};

